package com.beau.filter;

import com.beau.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 没有 token 的请求，一律拦截
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie token = cookies.getFirst("token");

        // token 不存在，拦截
        if (token == null) {
            // 对于登录、注册和邮件发送相关请求，不用拦截
            String path = request.getURI().getPath();
            logger.info("request path is " + path);
            if (path.startsWith("/api/user/login/") || path.startsWith("/api/user/register/")
                    || path.startsWith("/api/user/isRegistered")
                    || path.startsWith("/api/code/create/")
                    || path.startsWith("/api/create/")) {
                return chain.filter(exchange);
            }
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            logger.info("token 不存在，被拦截" + request.getURI().toString());
            String data = "request denied, please login";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        } else {
            // 对 token 进行校验
            String info = userService.info(token.getValue());
            // token 存在，但是非法
            if (StringUtils.isEmpty(info)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                logger.info("token 非法" + request.getURI().toString());
                String data = "request denied, please login";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
